package me.youline.dataServer.service.authentication;

import java.util.Date;

import me.youline.dataServer.entity.UserCredentialInfo;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Hash;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.crypto.hash.SimpleHash;

/**
 * 用户身份凭证业务辅助类，提供密码校验与密码加密的功能
 * 
 * @author linhan
 *
 */
public class UserCredentialInfoHelper  implements CredentialsMatcher {

	private String ALGORITHM_NAME = Sha256Hash.ALGORITHM_NAME;

	private int hashIterations = 1;

	private HashedCredentialsMatcher matcher;

	public UserCredentialInfoHelper() {
		this.matcher = new HashedCredentialsMatcher(ALGORITHM_NAME);
		this.matcher.setHashIterations(hashIterations);
	}

	@Override
	public boolean doCredentialsMatch(AuthenticationToken token,
			AuthenticationInfo info) {
		return matcher.doCredentialsMatch(token, info);
	}

	/**
	 * 根据用户提交凭证数据创建可用的用户凭证实体
	 * 
	 * @param token
	 *            用户提交的凭证数据
	 * @return
	 */
	public UserCredentialInfo getCredentialInfoByToken(AuthenticationToken token) {
		String salt = new SecureRandomNumberGenerator().nextBytes().toHex();
		String hash = this.encryptPassword(token.getCredentials(), salt);
		UserCredentialInfo info = new UserCredentialInfo(token.getPrincipal()
				.toString(), hash, salt);
		info.setCreateTime(new Date());
		return info;
	}

	/**
	 * 生成加密hash密码串
	 * 
	 * @param userPassword
	 * @param salt
	 * @return
	 */
	private String encryptPassword(Object userPassword, String salt) {

		Hash h = new SimpleHash(ALGORITHM_NAME, userPassword, salt,
				hashIterations);
		return h.toHex();
	}

}
